
Polymorphism is one of the primary pillars of object-oriented programming. Polymorphism allows you to invoke derived class methods through a base class reference during runtime. In the base class the method is declared virtual, and in the derived class we override the same method. The virtual keyword indicates, the method can be overridden in any derived class. Now given bellow the example code and explain the code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using testForClass1;
namespace testFor
{
public class Employee
{
public string _firstName = "Reza";
public string _lsatName = "Karim";
public virtual void printName()
{
Console.WriteLine(_firstName+" "+_lsatName);
}
}
public class FullTimeEmployee:Employee
{
public override void printName()
{
Console.WriteLine(_firstName + " " + _lsatName+ " -Full Time");
}
}
public class PartTimeEmployee:Employee
{
public override void printName()
{
Console.WriteLine(_firstName + " " + _lsatName + " -Part Time");
}
}
public class Program
{
static void Main(string[] args)
{
Employee[] empArray = new Employee[3];
empArray[0] = new Employee();
empArray[1] = new FullTimeEmployee();
empArray[2] = new PartTimeEmployee();
foreach (var myEmp in empArray)
{
myEmp.printName();
}
Console.Read();
}
}
}
In this code we write Employee class then the class contain two property and one method. This method responsible to print the first and last name. now we create another two class name as FullTimeEmployee and PartTimeEmployee then this two class under the printName method override also the parent class method as virtual using inherit the classes it’s called Polymorphism. Then create a array and called the method.